package com.morningstar.flow.antvX6;

import com.alibaba.fastjson2.JSON;
import com.morningstar.flow.antvX6.common.Node;
import com.morningstar.flow.antvX6.common.NodeParser;
import com.morningstar.flow.antvX6.edge.Edge;
import com.morningstar.flow.antvX6.node.*;
import com.morningstar.flow.dao.entity.FlowProcess;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class NodeConvert {

    public static final String CELLS_KEY = "cells";

    public static final String NODE_TYPE_KEY = "shape";


    public static Map<String, NodeParser> nodeParserMap = new HashMap<>();

    static {
        nodeParserMap.put(NodeStart.TYPE, new NodeStart());
        nodeParserMap.put(NodeEnd.TYPE, new NodeEnd());
        nodeParserMap.put(NodeUserTask.TYPE, new NodeUserTask());
        nodeParserMap.put(Edge.TYPE, new Edge());
        nodeParserMap.put(NodeCopyService.TYPE, new NodeCopyService());
        nodeParserMap.put(NodeExclusiveGateway.TYPE, new NodeExclusiveGateway());
        nodeParserMap.put(NodeIncludeGateway.TYPE, new NodeIncludeGateway());
        nodeParserMap.put(NodeParallelGateway.TYPE, new NodeParallelGateway());
    }

    public static List<Node> convert(FlowProcess flowProcess) {
        HashMap<String, Object> map = (HashMap<String, Object>) flowProcess.getProcessData();
        List<Object> cells = (List<Object>) map.get(CELLS_KEY);
        List<Node> nodes = new ArrayList<>(cells.size());
        for (Object object : cells) {
            log.info(JSON.toJSONString(object));
            HashMap<String, Object> cell = (HashMap<String, Object>) object;
            NodeParser nodeParser = nodeParserMap.get(cell.get(NODE_TYPE_KEY).toString());
            if (nodeParser != null) {
                nodes.add(nodeParser.parse(cell));
            }
        }
        return nodes;
    }
}
